#include "ourhdr.h"

/**
 * Usage: ./a.out 8 500 8>playground/practice_3.2.data 
 */
int main(int argc, char * argv[]) {
    int openmax;
    int tar_fd, src_fd;

    if (argc != 3) 
        err_quit("usage: a.out <descriptor-src#> <descriptor-target#>");

    openmax= open_max();
    
    src_fd= atoi(argv[1]);
    tar_fd= atoi(argv[2]);
    if (tar_fd >= openmax - 1) {
        printf("descriptor should less than %d\n", openmax - 1);
        exit(EXIT_FAILURE);
    }

    dup2(src_fd, tar_fd);

    printf("For test, I will write message \"Welcome to unix.\" to tar_fd %d\n", tar_fd);
    write(tar_fd, "Welcome to unix.", 16);
}

int dup2(int fd_src, int fd_tar) {
    int i, fd_tmp;
    int fd_arr[fd_tar+1];

    if (fd_src != fd_tar) {
        if ((fd_tmp= dup(fd_src)) != fd_tar) {
            if (fd_tmp > fd_tar) {  // fd_tar had be used 
                close(fd_tar);
                dup(fd_src);    // should be equal fd_tar

            } else {
                for (i= 0; i <= fd_tar; i++) {
                    fd_arr[i]= dup(fd_src);
                    if (fd_arr[i] < 0) 
                        err_sys("dup fd failed");

                    else if (fd_arr[i] == fd_tar)  // finded
                        break;

                    else if (fd_arr[i] > fd_tar) {     // is meaning fd_tar had used
                        close(fd_tar);
                        dup(fd_src);    // should be equal fd_tar
                        break; 
                        
                    }
                }

                if (fd_arr[i] < fd_tar) {
                    printf("cant dup fd_src %d to fd_tar %d\n", fd_src, fd_tar);
                    exit(1);
                }

                if (fd_arr[i] == fd_tar)
                    i--;

                // close fds that it add fd number to fd_tar
                while (i >= 0) {
                    close(fd_arr[i--]);
                }
            }
        }
    }
    close(fd_tmp);
    return fd_tar;
}

